/**
 * 封装微信的的request
 */
const WxApiRoot = '/api';
function GetQueryString(name)
{
   var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
   var r = window.location.search.substr(1).match(reg);
   if(r!=null)return unescape(r[2]); return null;
}
function request(url, data = {}, msg, method, header,type) {
	// 如果既有query和body那么就是application/json header提交
	if (header==true) {
		header ={'content-type': 'application/x-www-form-urlencoded'}
	} else {
		// body 用此方法提交            
		header = {
			 'Content-Type': 'application/json'
		}
	}
  if (!!msg) {
    uni.showLoading({
      title: msg, // 数据请求前loading
      mask:true
    })
  }
  return new Promise(function(resolve, reject) {
    uni.request({
      url: WxApiRoot + url,
      data: data,
      method: method,
      responseType: type || 'text',
      header: Object.assign(header, {
       
        'Authorization': uni.getStorageSync('token')
      }),
      success: function(res) {
        if (!!msg) {
			setTimeout(()=>{
				uni.hideLoading()
			},1000)
            
        }
        // 登陆失效，重新登陆
     if (res.data.code!=1) {
          let errorMessage = res.data.msg;
          uni.showToast({
            title: errorMessage,
            icon: 'none',
            duration:3000
          })
        }
        resolve(res.data)
      },
      fail: function(err) {
        if (!!msg) {
          uni.hideLoading()
        }
        let errorMessage = err.msg;
        uni.showToast({
          title: errorMessage,
          icon: 'none'
        })
        reject(err)
      }
    })
  });
}

function get(url, params, msg, header = {},type) {
  return request(url, params, msg, 'GET', header,type)
}

function post(url, data, msg, header = {}) {
  return request(url, data, msg, 'POST', header)
}
function deletes(url, data, msg, header = {}) {
  return request(url, data, msg, 'DELETE', header)
}
export default {
  get,
  post,deletes,GetQueryString,
  requestUrl:WxApiRoot
}
